
package durst.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ErrorResolution;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import durst.data.Account;
import durst.data.Event;
import durst.data.FileAccess;
import durst.data.UserCalendar;
import durst.data.dao.DaoFactory;
import durst.utils.BucketUtil;

@UrlBinding("/account/action/bucket/{account.id}/{event.id}/{filename}/")
public class BucketAction extends CalendarBasicAction {
	@ValidateNestedProperties({ @Validate(field = "id", required = true) })
	private Account account;

	@Validate(required = true, on = "!post")
	private String filename;

	@Validate(required = true, on = "post")
	private FileBean file;

	@ValidateNestedProperties({ @Validate(field = "id", required = true) })
	private Event event;

	public Resolution stream() {
		try {
			if (FileAccess.hasAccess(context.getAccount(), event, account)) {
				File file = BucketUtil.getFile(account, event, filename);
				return new StreamingResolution("application/octet-stream",
						new FileReader(file))
						.setFilename(filename).setAttachment(true);
			}
		} catch (FileNotFoundException err) {
		}
		return new ErrorResolution(404, "File Not Found!");
	}

	@DefaultHandler
	public Resolution post() throws IOException, SQLException {
		DaoFactory.getInstance().createDao(Event.class).refresh(event);
		DaoFactory.getInstance().createDao(UserCalendar.class)
				.refresh(event.getParent());

		if (event.getParent().getOwner().equals(context.getAccount()))
			if (ServletFileUpload.isMultipartContent(context.getRequest())) {
				file.save(BucketUtil.createFile(context.getAccount(), event,
						file.getFileName()));
			}

		return new ForwardResolution("/blank.jsp");
	}

	public Resolution delete() throws SQLException {
		if (FileAccess.hasAccess(context.getAccount(), event, account)) {

		}
		return new ForwardResolution("/blank.jsp");
	}

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public FileBean getFile() {
		return file;
	}

	public void setFile(FileBean file) {
		this.file = file;
	}

	public void setEvent(Event event) {
		this.event = event;
	}

	public Event getEvent() {
		return this.event;
	}
}